package tonytech.wordcode.service;

import tonytech.wordcode.mode.FileInfoImpl;
import tonytech.wordcode.mode.FileInfoMode;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * Created by WZTCM on 2017/1/16.
 */
public class FileInfoScanner implements FileInfoScannerServicempl {
    private final File file;
    private List<String> linesInfoList;

    FileInfoScanner(File file) {
        linesInfoList = new ArrayList<>();
        this.file = file;
    }

    @Override
    public void buildFileInfo() throws IOException {
        if (linesInfoList.size()!=0) return;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            getFileLines(br, getLinesFromBufferedReader());
        } catch (IOException e) {
            throwBuildFailedException(e);
            linesInfoList.clear();
        } finally {
            closeBufferReader(br);
        }
    }

    @Override
    public void buildFileWordInfo() throws IOException {

    }

    private Consumer<BufferedReader> getLinesFromBufferedReader() {
        return reader -> {
            try {
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    storeFileLine(line, str -> linesInfoList.add(str));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
    }

    private void getFileLines(BufferedReader br, Consumer<BufferedReader> consumer) {
        consumer.accept(br);
    }

    private void storeFileLine(String line, Consumer<String> consumer) {
        consumer.accept(line);
    }

    private void throwBuildFailedException(IOException e) throws IOException {
        e.printStackTrace();
        throw new IOException(e);
    }

    private void closeBufferReader(BufferedReader br) throws IOException {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                throwBuildFailedException(e);
            }
        }
    }

    @Override
    public FileInfoImpl getMode() {
        return new FileInfoMode(file, linesInfoList);
    }

    @Override
    public String toString() {
        return "FileInfoScanner{" +
                "linesInfoList=" + linesInfoList +
                '}';
    }
}
